<template>
<div :class="['merge', isDailog ? 'merge-dailog' : '', custType==='call'?'merge-call__dailog':'', isDailog&&searchShow ?'merge-serach__dailog':'', jumpMerge ? 'merge-serach__dailog':'']">
  <div class="sear" v-if="searchShow">
    <div class="search">
      <el-input
        size="mini"
        :placeholder="$t('public.pleaseEnter')"
        v-model.trim="input"
        @keyup.native.enter="getSearchWord">
        <el-select size="mini" v-model.trim="select.searchType" slot="prepend" :placeholder="$t('public.pleasePick')" >
          <el-option :label="$t('customer.merge.megLabel0')" value="displayName"></el-option>
          <el-option :label="$t('customer.merge.megLabel2')" value="phone"></el-option>
          <el-option :label="$t('customer.merge.megLabel3')" value="email"></el-option>
          <el-option :label="$t('customer.merge.megLabel4')" value="weixin"></el-option>
        </el-select>
        <i
          class="el-input__icon el-icon-search"
          slot="suffix"
          @click="getSearchWord">
        </i>
      </el-input>
      <advanced-search-new
        class='customAdvSearch'
        ref="advSearch"
        :type="'customer'"
        :searchType="'customAdvSearch'"
        :adv="search.customer_all.isChildren.adv"
        :formItemsConfig="formItemsConfigs"
        @selectChange="handlerSelectChange"
        @advSearch="advSearch"
        @confirmNewItemsConfig="handleConfirmNewItemsConfig"
      >
      </advanced-search-new>
    </div>

    <pagination
        :small="true"
        :currentPage="trunPage"
        :count="count"
        @turnPage="trunPages"
        :totalPage="Math.ceil(count/10)"
      >
    </pagination>
  </div>
  <div class="tip" v-if="isresult === false">
    <p>{{$t('customer.merge.megSearch')}}</p>
  </div>
  <div id="merge-table__hidepoint" v-if="isresult===true && !loading" v-loading="tableData.length<0">
    <el-table :data="tableData"
    highlight-current-row
    size="mini"
    stripe>
        <el-table-column
        v-if = "tableData.length>0"
        width="55">
          <template scope="scope">
            <el-radio size="mini" class="radio"  @click.native.prevent="getRow(scope.$index, tableData)" v-model.trim="radio" :label="scope.$index">{{labelBlank}}</el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" :label="$t('customer.merge.megLabel1')">
        </el-table-column>
        <el-table-column prop="phone" :label="$t('customer.merge.megLabel2')">
        </el-table-column>
        <el-table-column prop="email" :label="$t('customer.merge.megLabel3')" >
        </el-table-column> -->
        <template v-for="(item,index) in headers">
          <el-table-column
            v-if="item.name === 'status' && item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
             <template slot-scope="scope">{{ scope.row.statusName }}</template>
          </el-table-column>
          <el-table-column
            v-else-if="item.name === 'custsource1' && item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
             <template slot-scope="scope">{{ scope.row.sourceLabel }}</template>
          </el-table-column>
          <el-table-column
            v-else-if="item.name === 'categoryId' && item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
             <template slot-scope="scope">{{ scope.row.categoryIdLabel }}</template>
          </el-table-column>
          <el-table-column
            v-else-if="item.name === 'owner' && item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
             <template slot-scope="scope">{{ scope.row.ownerLabel }}</template>
          </el-table-column>
          <el-table-column
            v-else-if="item.name === 'CallTime' && item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
             <template slot-scope="scope">{{ scope.row.lastCallTime }}</template>
          </el-table-column>
          <el-table-column
            v-else-if="item.show"
            :label="item.label"
            :prop="item.name"
            :key="index"
            show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row[item.name] ? scope.row[item.name] : '' }}</template>
          </el-table-column>
        </template>
         <el-table-column  fixed="right" width="50">
            <template slot="header" slot-scope="scope">
              <el-popover
                placement="bottom-end"
                title="自定义表头"
                width="200"
                trigger="click">
                <div>
                <div class="item">
                  <search-checkbox :headerData="headers" @onCheckChange="handleCheckChange" ></search-checkbox>
                </div>
                </div>
                <span slot="reference" class="icon iconfont icon-gongjulanshezhi"></span>
              </el-popover>
            </template>
        </el-table-column>
    </el-table>
  </div>
  <div class="wrapper">
   <el-button v-if="!searchShow" class="primary_btn" @click.native.stop="closeDialog">{{$t('public.cancel')}}</el-button>
   <el-button type="primary" class="primary_btn" @click.native.prevent="submit">{{$t('public.save')}}</el-button>
  </div>
</div>
</template>
<script>
  import { isEmpty } from 'lodash'
  import * as types from '@/store/modules/webchat/mutation-types.js'
  import { isHideTel } from '@/utils/customerUtils.js'
  import { checkHideTel } from '@/utils/m7Utils'
  import Pagination from '@/components/public-modules/card/Pagination'
  import AdvancedSearchNew from '@/components/public-modules/card/search/Advanced1Search'
  import { sortCustomFields } from '@/utils/customerUtils.js'
  import { deepClone } from '@/utils/m7Utils'
  import searchCheckbox from './base/searchCheckbox.vue'
  import { filterAllCategory } from '@/utils/customerUtils.js'
  export default {
    name: 'Merge',
    data () {
      return {
        radio: -1,
        trunPage: 1,
        realCombox: '',
        tempHideTel: '',
        loading: true,
        isresult: true,
        isShowHearder: false,
        tableData: [],
        custType: '', // 判断业务类型
        multipleSelection: [],
        input: '',
        mergeCustomer: null,
        count: 0,
        labelBlank: '',
        isClick: false, // 表头操作按钮的显隐
        search: {
          isSearch: false,
          placeHolder: this.$t('customer.enterNameOrPhoneForQuery'),
          customer_all: {
            pagination: {
              small: true,
              currentPage: 1
            },
            show: true,
            isChildren: {
              lastQuery: null,
              rel: true,
              select: [],
              nomal: true,
              refresh: true,
              nomalForm: { value: '', query: '' },
              adv: {
                form: { categoryId: null, status: null, name: null, phone: null, actionType: [], custsource1: null, province: null, city: null, district: null, lastUpdateTime: [], createTime: [], batchNo: null, notifyTime: [], ownercom: null, owner: null, ownerdep: null, noContactedTime: [], CallTime: [], noCallTime: [], custom: {} },
                advSearchOptions: {
                  localed: [],
                  custom: []
                }
              },
              badgeList: {}
            }
          }
        },
        formItemsConfigs: {},
        headers:[
          { label: '客户名', name: 'name', show: true },
          { label: '电话', name: 'phone', show: true },
          { label: '邮箱', name: 'email', show: true },
        ],
        checkInit: false, // 是否初始化
        currentItemName: '',
        editingFormItemsConfig: null,
        formItems:[],
        formItemList:[],
        statusList:[], // 客户状态列表
        sources:[], // 数据来源列表
        custCategorys:[], // 公海来源列表
        optionData:[], // 所属范围
        customFieldList:[]
      }
    },
    props: {
      custInfo: Object,
      isDailog: Boolean,
      isDalog: {
        type: Boolean,
        default: false
      },
      callScreen: {
        type: Boolean,
        default: false
      },
      jumpMerge: Boolean,
      select: {
        type: Object,
        default: function () {
          return {
            searchType: 'displayName',
            searchWord: ''
          }
        }
      },
      bindCustomer: {
        type: Object,
        default: function () {
          return {
            searchShow: true,
            custObj: null,
            form: null
          }
        }
      },
    },
    components: {
      Pagination,
      AdvancedSearchNew,
      searchCheckbox
    },
    computed: {
      isHideTel () {
        return isHideTel(this.$store.state.session.user)
      },
      tableCust () {
        if (this.bindCustomer) {
          return this.bindCustomer.custObj
        }
      },
      searchShow () {
        if (!this.bindCustomer) {
          return true
        } else {
          return this.bindCustomer.searchShow
        }
      },
    },
    methods: {
      webchatAutoCust (sessionId) {
        return this.$store.state.webchat.autoCust[sessionId]
      },
      submit () {
        if (this.mergeCustomer) {
          this.$store.dispatch('queryCustomerInfo', { _id: this.mergeCustomer._id }).then(customer => {
            this.mergeCustomer.custInfo = customer
            this.$emit('change-merge', this.mergeCustomer)
          })
        } else {
          this.$message({
            message: this.$t('customer.merge.megChoseCust'),
            type: 'warning'
          })
        }
      },
      closeDialog () {
        this.$emit('closeDialog')
      },
      getRow (index, rows) {
        this.radio = +index
        this.mergeCustomer = rows[index]
      },
      getSearchWord (page) {
        let combox = this.input
//        ‘并入已存在客户’方式搜索的时候允许为空
        if (!this.input) {
          this.$message.error(this.$t('customer.searchConditionNoEmpty'))
          return
        }
        if (isNaN(page)) {
          page = 1
          this.trunPage = 1
        }
        let form = {
          isSearchWord: true,
          field: this.select.searchType,
          combox,
          page: page,
          limit: 10,
          setTodo: true
        }
        this.getData(form)
      },
      getData (form) {
//      setTodo用于区别在线咨询的‘自动定位客户’和‘并入已存在客户’传参方式
        let flag = form.isSearchWord
        let webchatFlag = form.setTodo
        delete form.isSearchWord
        delete form.setTodo
        let field = form.field
        let combox = form.combox
        let page = form.page || 1
        let res = {}
        res = {
          field,
          combox,
          page,
          limit: 10
        }
        if (form.isBind) {
          res.displayName = form.displayName
        }
        if (this.isHideTel && this.bindCustomer && this.bindCustomer.form && this.bindCustomer.form.field === 'phone' && this.realCombox && !flag && form.field === 'phone') {
          res.phone = this.realCombox
        }
        if (this.tempHideTel === this.input) {
          res.phone = this.realCombox
        }
        let action = 'queryCustomerByPopup'
        if (this.$route.path.split('/')[2] === 'webchat' && !webchatFlag && !this.callScreen) { // !callScreen 不是外呼弹屏,解决在线咨询模块弹出外呼弹屏action错误的问题
//      在线咨询增加了importSid匹配客户机制
          let importSid = ''
          if (this.webchatAutoCust(this.$route.path.split('/')[4])) {
            importSid = this.webchatAutoCust(this.$route.path.split('/')[4]).importSid || ''
          }
          let autoCust = this.$store.state.webchat.autoCust[this.$route.path.split('/')[4]]
          if (!autoCust) {
            autoCust = {
              autoCustPhone: '',
              autoCustName: ''
            }
          }
          res = {
            phone: form.phone ? form.phone : autoCust.autoMatchContent ? autoCust.autoMatchContent : '',
            displayName: form.displayName ? form.displayName : autoCust.autoMatchContent ? autoCust.autoMatchContent : '',
            importSid,
            page,
            limit: 10
          }
//          }
          action = 'queryCustomerByPopupNew'
        } else if (this.$route.path.split('/')[2] === 'call') {
          if (res.phone && this.isHideTel) {
            res.combox = res.phone
            console.log(res.combox)
          }
        }
        this.$store.dispatch(action, res).then(val => {
          this.$set(this, 'radio', -1)
          this.$set(this, 'mergeCustomer', null)
          this.renderData(val)
        })
      },
      trunPages (pageNum) {
        this.trunPage = pageNum
        this.getSearchWord(pageNum)
      },
      hideTel (tel) {
        return checkHideTel(tel, this.$store.state.session.user)
      },
      renderData (val) {
        this.loading = true
        if (this.count !== val.count) {
          this.count = val.count
          this.trunPage = 1
        }
        if (this.custType === 'webchat') {
          val.count = this.count
          let importSid = ''
          if (this.$store.state.webchat.autoCust[this.$route.path.split('/')[4]]) {
            importSid = this.$store.state.webchat.autoCust[this.$route.path.split('/')[4]].importSid || ''
          }
          let autoCust = this.$store.state.webchat.autoCust[this.$route.path.split('/')[4]]
          if (!autoCust) {
            autoCust = {
              autoCustPhone: '',
              autoCustName: ''
            }
          }
          let info = {
            autoCustName: autoCust.autoCustName,
            autoCustPhone: autoCust.autoCustPhone,
            autoMatchContent: autoCust.autoMatchContent,
            autoMatchType: autoCust.autoMatchType,
            autoCustObj: val,
            autoCustLength: val.list.length || 0,
            importSid: importSid
          }
          this.$store.commit(types.AUTO_CUST_INFO, {sessionId: this.$route.path.split('/')[4], data: info})
        }
        this.tableData = val.list.map(table => {
          table.phone = table.phone && table.phone.map(va => {
            if (this.isHideTel) {
              return this.hideTel(va.tel)
            }
            return va.tel
          }) + ''
          table.email = table.email && table.email.map(v => {
            return v.email
          }) + ''
          table.weixin = table.weixin && table.weixin.map(v => {
            return v.num
          }) + ''
          // 处理需转换的字段
          table.statusName = this.getName(this.statusList,table.status)
          table.sourceLabel = this.getName(this.sources,table.custsource1)
          table.categoryIdLabel = this.getName(this.custCategorys,table.categoryId)
          this.optionData.forEach(item=>{
            if(item.children && item.children.length) {
              item.children.forEach(i=>{
                if(i._id == table.owner) {
                  table.ownerLabel = i.label
                }
              })
            }
          })
          this.customFieldList.forEach(item => {
            if(Object.keys(table).indexOf(item.name) > 0) {
              let str = ''
              if(item.data && Array.isArray(item.data)) {
                console.log(item,item.data,'data')
                if(item.inputType === 'checkbox') {
                  item.data.forEach(val => {
                    let customValue = val.value.split('__')[0]
                    let list = deepClone(table[item.name])
                    if(list) {
                      list.forEach(res=>{
                        if(res == customValue) {
                          str += val.value.split('__')[1] + ' '
                        }
                      })
                    }
                  })
                  table[item.name] = str
                } else {
                  item.data.forEach(val => {
                    let customValue = val.value.split('__')[0]
                    if(customValue === table[item.name]) {
                      table[item.name] = val.value.split('__')[1]
                    }
                  })
                }
              }
            }
          })
          return table
        })
        this.loading = false
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs = formItemsConfig

        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'CustCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      },
      
      handlerSelectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue
        let form = this.search['customer_all'].isChildren.adv.form
        // 省市的数据拼接
        if (selectName === 'areaLinkage') {
          for (let key in selectValue) {
            form[key] = selectValue[key] ? selectValue[key] : ''
          }
        }
        // 级联的数据处理
        if (selectName === 'cascader') {
          if (selectObj.custom) {
            form.custom[selectObj.name] = selectValue
          } else {
            form[selectObj.name] = selectValue
          }
        }
        // 公海的数据处理
        if (selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') {
          form.ownercom = null
          form.owner = null
          form.ownerdep = null
          form[selectName] = selectValue
        }
      },

          advSearchBack (searchQuery) {
        let tmpObj = {}
        for (let key in searchQuery) {
          let value = searchQuery[key]
          if (value && typeof value === 'string') {
            if (value.match(/__/)) {
              let valSplit = value.split('__')
              tmpObj[key] = valSplit[1]
              searchQuery[key] = valSplit[0]
            } else {
              tmpObj[key] = value
            }
          }
          if (value && Array.isArray(value) && value.length > 0) {
            let tmpArr = []
            let tmpArr2 = []
            let nameArr= []
            for (let i = 0; i < value.length; i++) {
              if(Array.isArray(value[i])){
                let arr =  []
                let obj = []
                value[i].forEach(item=>{
                  let valSplit = item.split('__')
                  arr.push(valSplit[1])
                  obj.push(valSplit[0])
                })
                tmpArr2.push(obj)
                nameArr.push(arr)
              }else{
                let valSplit = value[i].split('__')
                tmpArr.push(valSplit[1])
                tmpArr2.push(valSplit[0])
              }
            }
            if(nameArr.length>0){
              nameArr.forEach(val=>{
                tmpArr += val.join(' ') + ';'
              })
              tmpArr = tmpArr.substring(0, tmpArr.lastIndexOf(";"));
              tmpObj[key] = tmpArr
              searchQuery[key] = tmpArr2
            }else{
              tmpObj[key] = tmpArr.join(';')
              searchQuery[key] = tmpArr2
            }
          }

          if (value && value.$in && Array.isArray(value.$in) && value.$in.length > 0) {
            let tmpArr = []
            let tmpArr2 = []
            for (let i = 0; i < value.$in.length; i++) {
              let valSplit = value.$in[i].split('__')
              tmpArr.push(valSplit[1])
              tmpArr2.push(valSplit[0])
            }
            tmpObj[key] = tmpArr.join(' ')
            searchQuery[key].$in = tmpArr2
          }

          if (value && value.$in && Array.isArray(value.$in) && value.$in.length === 0) {
            searchQuery[key] = null
          }
        }

        return tmpObj
      },
      
      advSearch (reset) {
         window._hmt && window._hmt.push(['_trackEvent', '其他统计', 'customer_all' + ' 高级搜索'])
        this.allCount = 0
        this.loading = true
        this.search.initSearch = true
        if (reset) {
          this.clearSearchQuery()
        }
        // 清空快捷搜索字段
        this.search['customer_all'].isChildren.nomalForm.query = ''
        this.search['customer_all'].isChildren.nomalForm.value = ''
        let form = this.search['customer_all'].isChildren.adv.form
        let searchQuery = deepClone(form)
        // 处理deepClone导致Date对象丢失
        for (let key in form.custom) {
          if (form.custom[key] instanceof Date) {
            searchQuery.custom[key] = new Date(form.custom[key].getTime())
          }
        }
        let custom = searchQuery.custom
        let createTime = form.createTime
        let lastUpdateTime = form.lastUpdateTime
        let notifyTime = form.notifyTime
        let noContactedTime = form.noContactedTime
        let noCallTime = form.noCallTime
        let CallTime = form.CallTime
        // 电话
        if (searchQuery.phone) {
          let tel = searchQuery.phone
          searchQuery['phone.tel'] = tel
          delete searchQuery.phone
        }

        // 是否建立联系计划
        if (searchQuery.actionType.length > 0) {
          searchQuery.actionType = searchQuery.actionType[0]
        }

        // 创建时间
        if (createTime) {
          if (createTime[0]) {
            searchQuery.createTime_begin_date = getFormatDateTime(createTime[0])
          }
          if (createTime[1]) {
            searchQuery.createTime_end_date = getFormatDateTime(createTime[1])
          }
          delete searchQuery.createTime
        }

        // 更新时间
        if (lastUpdateTime) {
          if (lastUpdateTime[0]) {
            searchQuery.lastUpdateTime_begin_date = getFormatDateTime(lastUpdateTime[0]).substring(0, 16)
          }
          if (lastUpdateTime[1]) {
            searchQuery.lastUpdateTime_end_date = getFormatDateTime(lastUpdateTime[1]).substring(0, 16)
          }
          delete searchQuery.lastUpdateTime
        }

        // 最近未联系客户时间
        if (noContactedTime) {
          if (noContactedTime[0]) {
            searchQuery.noContactedTime_begin = getFormatDateTime(noContactedTime[0]).substring(0, 16)
          }
          if (noContactedTime[1]) {
            searchQuery.noContactedTime_end = getFormatDateTime(noContactedTime[1]).substring(0, 16)
          }
          delete searchQuery.noContactedTime
        }
        // 最近未通话客户时间
        if (noCallTime) {
          if (noCallTime[0]) {
            searchQuery.noCallTime_begin_date = getFormatDateTime(noCallTime[0]).substring(0, 16)
          }
          if (noCallTime[1]) {
            searchQuery.noCallTime_end_date = getFormatDateTime(noCallTime[1]).substring(0, 16)
          }
          delete searchQuery.noCallTime
        }
        // 通话时间
        if (CallTime) {
          if (CallTime[0]) {
            searchQuery.CallTime_begin_date = getFormatDateTime(CallTime[0]).substring(0, 16)
          }
          if (CallTime[1]) {
            searchQuery.CallTime_end_date = getFormatDateTime(CallTime[1]).substring(0, 16)
          }
          delete searchQuery.CallTime
        }
        // 联系时间
        if (notifyTime) {
          if (notifyTime[0]) {
            searchQuery.notifyTime_begin_date = getFormatDateTime(notifyTime[0])
          }
          if (notifyTime[1]) {
            searchQuery.notifyTime_end_date = getFormatDateTime(notifyTime[1])
          }
          delete searchQuery.notifyTime
        }
        let _customerArr = this.search['customer_all'].isChildren.adv && this.search['customer_all'].isChildren.adv.advSearchOptions.custom
        // 自定义字段
        for (let key in custom) {
          // 处理自定义字段中的日期
          if (custom[key] instanceof Array) {
            for (let i = 0; i < _customerArr.length; i++) {
              if (_customerArr[i].name === key && _customerArr[i].inputType === 'date') {
                let _str = ''
                if (custom[key][0]) {
                  _str += getDateTime(custom[key][0], 'date')
                }
                if (custom[key][1]) {
                  _str += '_' + getDateTime(custom[key][1], 'date')
                }
                searchQuery[key + '_customDate'] = _str
                delete custom[key]
                delete searchQuery[key]
              } else if (_customerArr[i].name === key && _customerArr[i].inputType === 'datetime') {
                let _str = ''
                if (custom[key][0]) {
                  _str += getFormatDateTime(custom[key][0])
                }
                if (custom[key][1]) {
                  _str += '_' + getFormatDateTime(custom[key][1])
                }
                searchQuery[key + '_customDateTime'] = _str
                delete custom[key]
                delete searchQuery[key]
              } else {
                searchQuery[key] = custom[key]
              }
            }
            continue
          } else {
            searchQuery[key] = custom[key]
          }
        }
        delete searchQuery.custom

        let tempObj = this.advSearchBack(searchQuery)
        this.search['customer_all'].isChildren.adv.badgeList = tempObj

        Object.assign(searchQuery, {
          menu: 'customer_all',
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        })
        this.search['customer_all'].pagination.currentPage = searchQuery.page
        this.search['customer_all'].isChildren.lastQuery = searchQuery
        this.getCustList(this.$store, 'customer_all', searchQuery).then(() => {
          this.loading = false
        })
      },
      
      getCustList (store, tabName, query) {
        let _data = deepClone(query)
        _data.queryCount = true
        this.qu = _data
        return store.dispatch('queryCustomerList', query).then((resp) => {
          // if (query.page === 1) {
          //   this.pages = this.count / this.PAGE_SIZE
          // }
          if (resp && resp.success) {
            this.tableData = resp.list.map(table => {
              table.phone = table.phone && table.phone.map(va => {
                if (this.isHideTel) {
                  return this.hideTel(va.tel)
                }
                return va.tel
              }) + ''
              table.email = table.email && table.email.map(v => {
                return v.email
              }) + ''
              // 处理需转换的字段
              table.statusName = this.getName(this.statusList,table.status)
              table.sourceLabel = this.getName(this.sources,table.custsource1)
              table.categoryIdLabel = this.getName(this.custCategorys,table.categoryId)
              this.optionData.forEach(item=>{
                if(item.children && item.children.length) {
                  item.children.forEach(i=>{
                    if(i._id == table.owner) {
                      table.ownerLabel = i.label
                    }
                  })
                }
              })
              this.customFieldList.forEach(item => {
                if(Object.keys(table).indexOf(item.name) > 0) {
                  let str = ''
                  if(item.data && Array.isArray(item.data)) {
                    if(item.inputType === 'checkbox') {
                      item.data.forEach(val => {
                        let customValue = val.value.split('__')[0]
                        let list = deepClone(table[item.name])
                        if(list) {
                          list.forEach(res=>{
                            if(res == customValue) {
                              str += val.value.split('__')[1] + ' '
                            }
                          })
                        }
                      })
                      table[item.name] = str
                    } else {
                      item.data.forEach(val => {
                        let customValue = val.value.split('__')[0]
                        if(customValue === table[item.name]) {
                          table[item.name] = val.value.split('__')[1]
                        }
                      })
                    }
                  }
                }
              })
              return table
          })
        }
        })
      },
      handleLocaledOptions (custTmpl, custCategorysCache) {
        let statuses = [{ label: this.$t('public.all'), value: '' }]
        for (let key in custTmpl.status) {
          statuses.push({ label: custTmpl.status[key], value: `${key}__${custTmpl.status[key]}` })
        }
        this.statusList = statuses
        let sources = [{ label: this.$t('public.all'), value: '' }, { label: this.$t('customer.noSource'), value: `NA__${this.$t('customer.noSource')}` }, ...custTmpl.source.map(source => ({ label: source.name, value: `${source.key}__${source.name}` }))]
        this.sources = sources
        let custCategorys = [{ label: this.$t('public.all'), value: '' }, ...custCategorysCache.map(category => ({ label: category.cName, value: `${category._id}__${category.cName}` }))]
        this.custCategorys = custCategorys

        let localedOptions = [
          { label: this.$t('customer.categorySource'), filterable: true, name: 'categoryId', inputType: 'select', data: custCategorys },
          { label: this.$t('customer.custStatus'), filterable: true, name: 'status', inputType: 'select', data: statuses },
          { label: this.$t('business.customerName'), name: 'name', inputType: 'input' },
          { label: this.$t('customer.custCall'), name: 'phone', inputType: 'input' },
          { label: this.$t('customer.hasContactPlan'), name: 'actionType', inputType: 'checkbox', data: [{ label: this.$t('public.yes'), value: `date__${this.$t('customer.hasContactPlan')}` }] },
          { label: this.$t('customer.dataSource'), filterable: true, name: 'custsource1', inputType: 'select', data: sources },
          { label: this.$t('public.provinceCity'), name: 'area', inputType: 'area', provinceName: 'province', provinceValue: this.search['customer_all'].isChildren.adv.form.province, cityName: 'city', cityValue: this.search['customer_all'].isChildren.adv.form.city, districtName: 'district', districtValue: this.search['customer_all'].isChildren.adv.form.district },
          { label: this.$t('km.updateTime'), name: 'lastUpdateTime', inputType: 'time' },
          { label: this.$t('public.createTime'), name: 'createTime', inputType: 'time' },
          { label: this.$t('customer.noContactedTime'), name: 'noContactedTime', inputType: 'time' },
          { label: this.$t('customer.noCallTime'), name: 'noCallTime', inputType: 'time' },
          { label: this.$t('customer.CallTime'), name: 'CallTime', inputType: 'time' },
          { label: this.$t('customer.importBatch'), name: 'batchNo', inputType: 'input' },
          { label: this.$t('customer.contactPlan.contactPlanTime'), name: 'notifyTime', inputType: 'time' }
        ]
        return localedOptions
      },
      handleCustomOptions (custTmpl) {
        let customForm = {}
        let customOptions = []
        let sortedCustomFields = sortCustomFields(custTmpl.custom_fields)
        sortedCustomFields.forEach(customField => {
          let option = { label: customField.name, name: customField._id }
          // 启用的
          if(customField.status !== 'stop') {
            if (customField.type === 'single') {
              option.inputType = 'input'
            } else if (customField.type === 'multi') {
              option.inputType = 'textarea'
            } else if (customField.type === 'number') {
              option.inputType = 'input'
              option.validateType = 'Number'
            } else if (customField.type === 'dropdown') {
              if (customField.dic) {
                option.inputType = 'cascader'
                option.data = customField.dic
                option.props = { multiple: true , 'collapse-tags':true, clearable: true}
              } else {
                option.inputType = 'select'
                option.data = []
                for (let key in customField.choices) {
                  let label = customField.choices[key] || ' '
                  option.data.push({ label, value: `${key}__${customField.choices[key]}` })
                }
              }
            } else if (customField.type === 'checkbox' || customField.type === 'radio') {
              option.inputType = customField.type
              option.data = []
              for (let key in customField.choices) {
                option.data.push({ label: customField.choices[key], value: `${key}__${customField.choices[key]}` })
              }
            } else {
              option.inputType = customField.type
            }
  
            customOptions.push(option)
  
            if (customField.type === 'checkbox') {
              customForm[customField._id] = []
            } else if (customField.type === 'date') {
              customForm[customField._id] = ''
            } else if (customField.type === 'dropdown' && !customField.dic) {
              customForm[customField._id] = {$in: []}
            } else {
              customForm[customField._id] = null
            }
          }
        })
        let _obj = {
          customForm: customForm,
          customOptions: customOptions
        }
        this.customFieldList.push(...customOptions)
        return _obj
      },
      searchInit () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'custCategorys' }),
          this.$store.dispatch('getCache', { type: 'custTmpls' }),
          this.$store.dispatch('getCache', { type: 'quickSearchTmpls' })
        ]).then(([custCategorysCache, custTmpls, quickSearchTmpls]) => {
          if (custTmpls.length <= 0) { // 新开的账户，没有数据
            this.$data.newEmptySeat = true
            return
          } else {
            this.$data.newEmptySeat = false
          }
          let custTmpl = custTmpls[0]
          // 处理固定查询字段
          let localedOptions = this.handleLocaledOptions(custTmpl, custCategorysCache)
          let isFieldAdded = (fieldName) => fieldName === 'province' || fieldName === 'city' || fieldName === 'name' || fieldName === 'phone' || fieldName === 'district'
          let stableFieldsDefaultValue = {}
          custTmpl.stable_fields.forEach(stableField => {
            if (stableField.search && !isFieldAdded(stableField.name)) {
              localedOptions.push({ label: stableField.value, name: stableField.name, inputType: 'input' })
              stableFieldsDefaultValue[stableField.name] = ''
            }
          })
          // 处理自定义字段
          let _obj = this.handleCustomOptions(custTmpl)
          let localedOptionsCopy = deepClone(localedOptions)
          let quickSelect = [{ label: this.$t('public.all'), value: '' }]
          localedOptionsCopy.push({ label: this.$t('customer.owner'), name: 'owner', inputType: 'owner' })
          // 客户状态
          for (let key in custTmpl.status) {
            quickSelect.push({ label: custTmpl.status[key], value: key })
          }
          // 自定义快捷搜索
          quickSearchTmpls.forEach(quickSearchTmpl => {
            if (quickSearchTmpl.menu === 'customer_all') {
              quickSelect.push({ label: quickSearchTmpl.kName, isCustomize: true, query: quickSearchTmpl.query, value: quickSearchTmpl._id })
            }
          })
          this.search['customer_all'].isChildren.select = quickSelect
          this.search['customer_all'].isChildren.adv.form = Object.assign({}, this.search['customer_all'].isChildren.adv.form, stableFieldsDefaultValue)
          this.search['customer_all'].isChildren.adv.advSearchOptions.localed = localedOptionsCopy
          this.search['customer_all'].isChildren.adv.advSearchOptions.custom = deepClone(_obj.customOptions)
          this.search['customer_all'].isChildren.adv.form.custom = deepClone(_obj.customForm)
          this.isFirst = true
          console.log('init')
        })
      },
      handleCheckChange(Datalist, isInit){
        // 表头配置变化
        if (this.checkInit && isInit === true) {
          // 是否是初始化
          return
        }
        if (isInit === true) {
          this.checkInit = true
        }
        // this.headers = Datalist
        if(isInit) {
          return
        }
        this.$set(this,'headers',Datalist)
        try{
          let sessionId = this.$store.state.session.sessionId
          window.localStorage.setItem(sessionId + 'cuntomrFileds', JSON.stringify(this.headers))
        }catch(err){
          console.log(err)
        }
      },
      getFormItems () {
        let sessionId = this.$store.state.session.sessionId
        let customerFileds = JSON.parse(localStorage.getItem(sessionId + 'cuntomrFileds'))
        let resultList = []
        if (this.search['customer_all'].isChildren.adv && this.search['customer_all'].isChildren.adv.advSearchOptions) {
          var localed = this.search['customer_all'].isChildren.adv.advSearchOptions.localed
          var custom = this.search['customer_all'].isChildren.adv.advSearchOptions.custom

          var index = 0
          if (localed) {
            localed.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_localed'
              newItem._index = index++
              this.formItems.push(newItem)
            })
          }

          if (custom) {
            custom.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_custom'
              newItem._index = index++
              this.formItems.push(newItem)
            })
          }
        }
        this.formItems && this.formItems.forEach((item, index) => {
          var newItem = {
            label: item.label,
            name: item.name,
            hidden: false
          }
          if(item.data && item.data.isDic) {
          return
          } else {
            if (this.formItemsConfig && this.formItemsConfig[item.name]) {
              var config = this.formItemsConfig[item.name]
              newItem.hidden = config.hidden
            } else {
              newItem.hidden = false
            }
            resultList.push(newItem)
          }

        })
        let arr = ['name', 'email', 'phone', 'noCallTime', 'noContactedTime', 'categoryId', 'actionType', 'area']
        // 去除这几个字段
        this.formItemList = resultList.filter(item=>{
          return arr.indexOf(item.name) < 0
        })
        this.formItemList = Object.values(this.formItemList).map(item=>{
          return {
            name: item.name,
            show: item.hidden,
            label: item.label
          }
        })
        this.formItemList = [...this.headers, ...this.formItemList]
        if(customerFileds) {
          // 如果自定义字段又有添加重新把添加项加进去
          this.headers = customerFileds
          if(this.formItemList.length !== this.headers.length) {
            let arr = []
            let headerItem = []
            // 缓存中的数据还去缓存数据
            this.headers.forEach(item=>{
              arr.push(item.name)
              this.formItemList.forEach(item1=>{
                if(item.name === item1.name) {
                  headerItem.push(item)
                }
              })
            })
            // 新加的自定义字段加进去
            this.formItemList.forEach(item1 => {
              if(!arr.includes(item1.name)) {
                headerItem.push(item1)
              }
            })
            this.headers = headerItem
          }
        } else {
          this.headers = Object.values(this.formItemList).map(item=>{
            return {
              name: item.name,
              show: item.show,
              label: item.label
            }
          })
        }
      },
      // 获取表格中需转换的名字
      getName(list,val){
        let statusLabel = ''
        if(list && list.length > 0) {
          list.forEach(item=>{
            if(item.value.split('__')[0] == val) {
              statusLabel = item.label
            }
          })
        }
        return statusLabel
      },
    },
    watch: {
      isDalog (cur, pre) {
        if (cur) {
          initTable(this)
        } else {
          this.$set(this, 'tableData', [])
          this.$set(this, 'count', 0)
          this.$set(this, 'input', '')
          this.$set(this, 'radio', -1)
          this.$set(this, 'mergeCustomer', null)
          this.select && this.$set(this.select, 'searchType', 'displayName')
          this.bindCustomer && this.$set(this.bindCustomer, 'form', {})
        }
      }
    },
    beforeMount () {
      this.loading = true
      initTable(this)
      this.loading = false
      this.searchInit()
      // 高级搜索自定义布局配置
      this.$store.dispatch('getAdvSearchConfig', {
        searchType: 'CustCardGroup'
      }).then((configs) => {
        this.formItemsConfigs = configs || {}
        this.getFormItems()
      })
      // 所属范围的数据
      Promise.all([
        this.$store.dispatch('getCache', { type: 'depts' }),
        this.$store.dispatch('getCache', { type: 'agents' }),
        this.$store.dispatch('getCache', { type: 'custCategorys' })
      ]).then(([depts, agents]) => {
        let optionData = []
        let custCategorys = filterAllCategory()
        let emptyOption = {
          _id: '',
          label: this.$t('public.all'),
          type: 'ownercom'
        }
        let commonOption = {
          _id: 'common',
          label: this.$t('public.common'),
          children: [
            {_id: 'myself', type: 'ownercom', label: this.$t('public.myself')},
            {_id: 'my-subordinates', type: 'ownercom', label: this.$t('public.myAndMylower')},
            {_id: 'my-department', type: 'ownercom', label: this.$t('public.ownerDept')},
            {_id: 'my-subordinates-dept', type: 'ownercom', label: this.$t('public.ownerAndMyLowerDept')}
          ]
        }
        let noOwner = {_id: 'NA', type: 'owner', label: this.$t('customer.noOwner')}
        let _custCategorys = custCategorys.map(category => ({_id: category._id, type: 'owner', label: category.displayName, displayName: category.cName}))
        let _agents = agents.map(agent => ({_id: agent._id, type: 'owner', label: `${agent.displayName}[${agent.exten}]`, displayName: agent.displayName, pinyin: agent.pinyin}))
        let customerOwners = []
        let otherOwners
        if (this.isNotice) {
          customerOwners = [..._custCategorys, ..._agents]
          otherOwners = [..._agents]
        } else {
          customerOwners = [noOwner, ..._custCategorys, ..._agents]
          otherOwners = [noOwner, ..._agents]
        }
        let ownerOption = {
          _id: 'owner',
          label: this.businessType === 'customer' ? this.$t('customer.customerOwner') : this.$t('customer.customerWorker'),
          children: this.businessType === 'customer' ? customerOwners : otherOwners
        }
        let _depts = depts.filter(dept => dept.pId !== '')
        _depts = _depts.map(dept => ({ _id: dept._id, type: 'ownerdep', label: dept.name }))
        let deptOption = {
          _id: 'dept',
          label: this.$t('customer.customerDept'),
          children: _depts
        }
        if (this.isNotice) {
          optionData.push(...[emptyOption, ownerOption, deptOption])
        } else {
          optionData.push(...[emptyOption, commonOption, ownerOption, deptOption])
        }
        this.optionData = optionData
      })
    },
  }
  function initTable (vm) {
    let bc = vm.bindCustomer
    if (bc && !isEmpty(bc.form)) {
      vm.custType = 'webchat'
      if (bc.form.custType === 'call') {
        vm.custType = bc.form.custType
      }
      if (vm.isHideTel && bc.form.field === 'phone') {
        vm.tempHideTel = vm.hideTel(bc.form.combox)
        vm.$set(vm, 'input', vm.hideTel(bc.form.combox))
        vm.realCombox = bc.form.combox
      } else {
        vm.$set(vm, 'input', bc.form.combox)
      }
      // 当在线咨询模块 选了 客户名 和 电话  类型就是webchat 不用带到合并组件查询
      //
      if (bc.form.field === 'webchat' && vm.searchShow) {
        vm.$set(vm, 'input', '')
        vm.$set(vm.select, 'searchType', 'displayName')
      } else {
        vm.$set(vm.select, 'searchType', bc.form.field)
        vm.getData(bc.form)
      }
    }
    if (bc && !isEmpty(bc.custObj)) {
      vm.renderData(bc.custObj)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .merge
    overflow-y auto
    height 85%
    padding 30px 30px 0 30px
    .tip
      color $cf-gray1
      border 1px solid $c-border1
      border-top none
      background $c-back
      height 74px
      line-height 74px
      text-align center
    h4
      color $cf-gray1
      font-size 14px
      margin-bottom 16px
      font-weight normal
    .sear
      display flex
      justify-content space-between
      align-items center
      height 48px
      border 1px solid $c-border1
      span
        display inline-block
      .search
        width 300px
        display inline-block
        margin-left 16px
        position relative
        display flex
        .el-select
          width 96px
          margin-left 2px
    .icon-gongjulanshezhi
      cursor pointer
    .customAdvSearch
      display inline-block
  .wrapper
    margin-top 14px
    display block
    float right
  .merge-dailog
    // height 388px
  .merge-call__dailog
    height 90%
  .merge-serach__dailog
    // height 320px
  .wrapper
    position absolute
    left 0
    bottom 0
    width 100%
    border-radius 4px
    margin 0
    padding 4px 0
    background $cf-white
    z-index 6
    border-top 1px solid #dfe6ec
    text-align right
    border-top-left-radius 0
    border-top-right-radius 0
    .primary_btn
      margin-right 20px
.el-divider__text
  color #979ba3 !important
  font-size 12px !important
</style>
